// 和用户相关的状态管理

import { createSlice } from "@reduxjs/toolkit";
import { removeToken} from "@/utils";
import { setToken as _setToken, getToken } from "@/utils";
import { loginAPI , getProfileAPI } from "@/apis/user";

const userStore = createSlice ({ 
    name:'user',
    initialState:{
        token:getToken() || '', // 字符串
        userInfo : {}
    },
    reducers:{
        setToken(state,action){
            state.token = action.payload
            // localStorage中多存一份
            _setToken(action.payload)
        },
        setUserInfo(state,action){
            state.userInfo = action.payload
        },
        clearUserInfo(state){
            state.token = ''
            state.userInfo = {}
            removeToken()
        }
    }
})

// 解构

const {setToken , setUserInfo , clearUserInfo} = userStore.actions

// 获取reducer函数

const userReducer = userStore.reducer

// 异步方法 完成登录获取token
const fetchLogin = (loginForm) =>{
    return async(dispatch) =>{
        // 1. 发送异步请求
        const res = await loginAPI(loginForm)
        // 2. 提交同步action进行token的存入
        dispatch(setToken(res.data.token))
    }
}

// 获取个人信息
const fetchUserInfo = () =>{
    return async(dispatch) =>{
      const res = await getProfileAPI()                                                               // 访问用户信息接口     
      dispatch(setUserInfo(res.data)) 
    }
}

// 导出
export{setToken ,fetchUserInfo , fetchLogin , clearUserInfo}

export default userReducer 